#!/usr/bin/python3
# -*-coding:utf-8 -*-

import csv
import os
from pathlib import Path
import sys
import utils

def get_csv(i: str, map: dict):

    column = []
    for version, scores in map.items():
        for sorce in scores:
            if sorce[0] not in column:
                column.append(sorce[0])
    
    print([" "] + column)
    # with open(file, "w", encoding="utf-8") as file:
    #     writer = csv.writer(file)
    #     writer.writerow([" "] + column)
        # for version, scores in map.items():

    pass

def grep(file: Path) -> str:
    with open(file, "r", encoding="utf-8") as ifile:
        lines = ifile.readlines()
        line = lines[4].strip()
        assert line.startswith("Elapsed (wall clock) time (h:mm:ss or m:ss):"), file
        return line.strip("Elapsed (wall clock) time (h:mm:ss or m:ss):")

def version_map(cwd: Path, files: list) -> dict:
    map = {}
    threads = []
    for file in files:
        version = file.split("-")[1]
        if version not in map:
            map[version] = []
    
    for file in files:
        version = file.split("-")[1]
        thread = file.split("-")[2]
        assert thread.startswith("t")
        thread = int(thread[1:])
        file = cwd.joinpath(file)
        time = grep(file)
        map[version].append((thread, time))
        if thread not in threads:
            threads.append(thread)
    
    # for version, scores in map.items():
        

    return map

def same_input(i: str, files: list) -> list:
    files_of_i = []
    for file in files:
        if (file.endswith("i" + i + ".txt")):
            files_of_i.append(file)
    return files_of_i

if __name__ == '__main__':
    if len(sys.argv) == 2:
        i = sys.argv[1]
        cwd = utils.pwd.joinpath("log")
        files_of_i = []
        for path, _, files in os.walk(cwd):  
            files = same_input(i, files)
            break
        map = version_map(cwd, files)
        for k, v in map.items():
            list.sort(v)
            print(k + "\t", v)
        get_csv(i, map)
    else:
        print(__file__, "<i>")
    pass
